package com.ls.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * APP 的签名助手，app需要单独签名的
 * <p>
 * Created by cubebox on 2019/7/5.
 */
public class WXAPPPayHelper {


    /**
     * app的单独签名
     *
     * @param appId      appid
     * @param prePayId   预订单的id
     * @param shanghuhao 商户号
     * @param APIKEY     apikey（微信商户后台自定义设置的key，不是secert）
     */
    public static String getAPPSign(String appId, String prePayId, String noncestr, String timestamp, String shanghuhao, String APIKEY) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("partnerid", shanghuhao);
        map.put("prepayid", prePayId);
        map.put("package", "Sign=WXPay");
//        map.put("noncestr", String.valueOf(System.nanoTime()));
        map.put("noncestr", noncestr);
//        map.put("timestamp", new BigDecimal(System.currentTimeMillis() * 0.001).longValue() + "");
        map.put("timestamp", timestamp);

        ArrayList<String> sortList = new ArrayList<>();
        sortList.add("appid");
        sortList.add("partnerid");
        sortList.add("prepayid");
        sortList.add("package");
        sortList.add("noncestr");
        sortList.add("timestamp");
        Collections.sort(sortList);

        StringBuilder md5 = new StringBuilder();
        int size = sortList.size();
        for (int k = 0; k < size; k++) {
            if (k == 0) {
                md5.append(sortList.get(k)).append("=").append(map.get(sortList.get(k)));
            } else {
                md5.append("&").append(sortList.get(k)).append("=").append(map.get(sortList.get(k)));
            }
        }
        String stringSignTemp = md5 + "&key=" + APIKEY;

        return Md5(stringSignTemp).toUpperCase();
    }

    private static String Md5(String s) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] e = s.getBytes(StandardCharsets.UTF_8);
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(e);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }
            return new String(str);
        } catch (Exception var10) {
            return null;
        }
    }
}
